<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AddressBook;
use App\Models\AddressBookLabel;
use App\Models\AdminRoleUser;
use App\Models\Article;
use App\Models\Course;
use App\Models\DoctorWorks;
use App\Models\Order;
use App\Models\OrderCaseDescribe;
use App\Models\VisitUser;
use App\Util\Tool;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

//use Encore\Admin\Controllers\Dashboard;
//use Encore\Admin\Layout\Column;
//use Encore\Admin\Layout\Content;
//use Encore\Admin\Layout\Row;

class HomeController extends Controller
{
    public function index()
    {

        $start = microtime(true);
        $userid = auth()->user()->id ?? 0;
        $types = auth()->user()->types;
        $hospital_id = auth()->user()->hospital_id;
        //判断用户是否是医院账号
        $role_list = AdminRoleUser::where(['user_id' => $userid])->pluck("role_id")->toArray();
        if (!$userid || $types != 4 || $hospital_id == 0 || !in_array(11, $role_list)) {
            return redirect("admin/auth/logout");
        }
        //开始读取数据
//        $isfollow_num = 0;
//        $nofollow_num = 0;
//        $patient_num = 0;
//        $today_patient_num = 0;
//        $total_article_num = 0;
//        $work_consult_ranking = [];
        $title = auth()->user()->name;
        $data['title'] = $title;
        $work_ids = (new DoctorWorks())->where(['status' => 1, 'hospital_id' => $hospital_id])->pluck("id")->toArray();
        $work_total = count($work_ids);
        $dayStart = Carbon::now()->startOfDay();
        $dayEnd = Carbon::now()->endOfDay();
//        if(!empty($work_ids)){
        //已随访的工作室数
        $isfollow_num = (new VisitUser())->whereBetween('created_at', [$dayStart, $dayEnd])->whereIn("work_id", $work_ids)->groupBy("work_id")->get()->count("id");//所有
        //未随访的工作室数
        $nofollow_num = $work_total - $isfollow_num;
//            患者数
        $patient_num = AddressBook::whereIn("work_id", $work_ids)->groupBy("user_id")->get()->count();
        //今日新增工作室数
        $today_work_num = DoctorWorks::whereBetween('created_at', [$dayStart, $dayEnd])->count();
//            Tool::start();
        //今日新增患者
        $today_patient_num = AddressBook::whereIn("work_id", $work_ids)->whereBetween('created_at', [$dayStart, $dayEnd])->groupBy("user_id")->get()->count();
//            Tool::ends();
        //今日新增文章数
        $total_article_num = Article::whereIn("work_id", $work_ids)->whereBetween('created_at', [$dayStart, $dayEnd])->count();
        //今日新增视频数
        $total_course_num = Course::whereIn("work_id", $work_ids)->whereBetween('created_at', [$dayStart, $dayEnd])->count();
        //今日新增咨询订单数
        $total_order_num = Order::whereIn("work_id", $work_ids)->whereIn("order_type", [3, 4])->whereIn("order_status", [0, 1])->where("pay_status", '=', 1)->whereBetween('pay_time', [$dayStart, $dayEnd])->count();
        //工作室咨询排名
        $work_consult_ranking = $this->getConsultRankList($work_ids);
        //工作室患者数排名
        $work_patient_number = $this->getPatientNumList($work_ids);
        //工作室创作内容排名
        $work_create_number = $this->getWorkCreateNumber($work_ids);
//            工作室参与咨询数
        $workconsultnum = $this->getWorkConsultNumber($work_ids);
//         工作室未参与咨询数
        $no_workconsultnum = $work_total - $workconsultnum;
//        }
        // 病种统计图
        $Disease_types = $this->getDiseaseTypesList($work_ids);
//            dump($Disease_types);
//                    患者年龄分布图
        $ageRadar = $this->getPatientNumAgeRadar($work_ids);
//        工作室参与咨询月统计
        $consultnummonth = $this->getConsultNumMonthStatistics($work_ids);
//        //工作室参与咨询日统计
        $consultnumday = $this->getConsultNumDayStatistics($work_ids);
//        $end = microtime(true);
//        $time = ($end - $start) * 1000; // 转换为毫秒
//        echo "执行时间: " . $time . " 毫秒\n";die;
        $data['work_total'] = $work_total; //工作室数
        $data['isfollow_num'] = $isfollow_num??0; //今日随访数
        $data['nofollow_num'] = $nofollow_num; //今日未随访数
        $data['patient_num'] = $patient_num; //患者数
        $data['today_work_num'] = $today_work_num; //今日新增工作室数
        $data['today_patient_num'] = $today_patient_num ?? 0; //今日新增患者数
        $data['total_article_num'] = $total_article_num ?? 0; //今日新增文章数
        $data['total_course_num'] = $total_course_num ?? 0; //今日新增课程数
        $data['total_order_num'] = $total_order_num ?? 0; //今日新增课程数
        $data['work_consult_ranking'] = $work_consult_ranking; //工作室咨询排序
        $data['work_patient_number'] = $work_patient_number; //工作室患者排序
        $data['work_create_number'] = $work_create_number; //工作室患者排序
        $data['workconsultnum'] = $workconsultnum ?? 0; //工作室参与咨询数
        $data['no_workconsultnum'] = $no_workconsultnum ?? 0; //工作室未参与咨询数
        $data['disease_types'] = $Disease_types; //病种图
        $data['ageRadar'] = $ageRadar; //年龄雷达图
        $data['consultnummonth'] = $consultnummonth; //咨询月统计
        $data['consultnumday'] = $consultnumday; //咨询月统计
        return view('admin.index', compact('data'));
    }


    /**
     * @param $w_ids
     * 咨询数每日统计
     */
    public function getConsultNumDayStatistics($w_ids)
    {
        $year = date('Y'); // 当前年份
        $month = date('m');
        $daysInMonth = (new \DateTime("{$year}-{$month}-01"))->format('t');
        $day_name = array();
        $day_value = [];
        if (empty($w_ids)) {
            for ($i=0;$i<$daysInMonth;$i++){
                $d = $this->getDayBeforeDays($i-1);
                $d = substr($d,5);
                $day_name[] = $d;
                $day_value[] = 0;
            }
            $list['day_name'] = $day_name;
            $list['day_value'] = $day_value;
        }
//        $date = Carbon::now()->toDateString() ." "."23:59:59";
//        $d_num = $this->getDayBeforeDays($daysInMonth);
//        $res = (new Order())
//                ->whereIn("work_id", $w_ids)
//                ->whereIn("order_type", [3, 4])
//                ->where("pay_status", '=', 1)
//                ->where("order_status", '<=', 1)
//                ->whereBetween('pay_time', [$date, $d_num])
//            ->select("pay_time")
//                ->get();
        for ($i = 1; $i <= $daysInMonth; $i++) {
            $d = $this->getDayBeforeDays($i-1);
            $day = substr($d,5);
            $day_name[] = $day;
            $start = $d.' '.'00:00:00';
            $end = $d . ' '.'23:59:59';
            $res = (new Order())
                ->whereIn("work_id", $w_ids)
                ->whereIn("order_type", [3, 4])
                ->where("pay_status", '=', 1)
                ->where("order_status", '<=', 1)
                ->whereBetween('pay_time', [$start, $end])
                ->count("id");
            $day_value[] = $res;
        }
        $list['day_name'] = $day_name;
        $list['day_value'] = $day_value;
        return $list;
    }







    /**
     * @param $w_ids
     * 咨询数每月统计
     */
    public function getConsultNumMonthStatistics($w_ids)
    {
        $age_name = array('1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月');
        $age_value = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        if (empty($w_ids)) {
            $list['age_name'] = $age_name;
            $list['age_value'] = $age_value;
        }
        foreach ($age_value as $k => $v) {
            $time = $this->getMonthStartEndTime($k + 1);
            $res = (new Order())
                ->whereIn("work_id", $w_ids)
                ->whereIn("order_type", [3, 4])
                ->where("pay_status", '=', 1)
                ->where("order_status", '<=', 1)
                ->whereBetween('pay_time', [$time['start'], $time['end']])
                ->count("id");
            $age_value[$k] += $res;
        }
        $list['month_name'] = $age_name;
        $list['month_value'] = $age_value;
        return $list;
    }


    /***
     * @param $month
     * 获取某月的开始时间和结束时间
     */
    public function getMonthStartEndTime($month)
    {
        $year = date('Y'); // 当前年份
        // 获取该月的第一天开始时间
        $startDate = Carbon::createFromDate($year, $month, 1)->startOfDay();
        // 获取该月的最后一天结束时间
        $endDate = Carbon::createFromDate($year, $month, 1)->endOfMonth()->endOfDay();
        $start = $startDate->toDateTimeString() . "\n"; // 输出：当前年某月的第一天开始时间
        $end = $endDate->toDateTimeString() . "\n"; // 输出：当前年某月的最后一天结束时间
        $time['start'] = $start;
        $time['end'] = $end;
        return $time;
    }


    /***
     * @param $w_ids
     * @return array
     * 年龄雷达图
     */
    public function getPatientNumAgeRadar($w_ids)
    {
        $age_name = array('1-18岁', '19-29岁', '30-39岁', '40-60岁', '61-80岁', '80以上');
        $age_value = [0, 0, 0, 0, 0, 0];
        if (empty($w_ids)) {
            $list['age_name'] = $age_name;
            $list['age_value'] = $age_value;
        }
//        $hospital_id = auth()->user()->hospital_id;
//        Tool::start();
        $res = (new AddressBook())->whereIn("work_id", $w_ids)
            ->groupBy("user_id")
            ->get();
//        $res = (new Order())
//            ->from("c_orders as order")
//            ->select("order_case.age")
//            ->leftjoin("c_order_case_describes as order_case", 'order.id', '=', 'order_case.order_id')
//            ->whereIn("order.work_id", $w_ids)
//            ->whereIn("order.order_type", [3, 4])
//            ->where("order.pay_status", '=', 1)
//            ->where("order.order_status", '<=', 1)
//            ->get();
//        $res = (new OrderCaseDescribe())
//            ->from("c_order_case_describes as order_case")
//            ->select("order_case.age")
//            ->leftjoin("c_orders as order", 'order.id', '=', 'order_case.order_id')
//            ->leftjoin("c_doctor_works as work", 'order.work_id', '=', 'work.id')
//            ->leftjoin("admin_users as user", 'user.hospital_id', '=', 'work.hospital_id')
//
////            ->whereIn("order.work_id", $w_ids)
//            ->whereIn("order.order_type", [3, 4])
//            ->where("order.pay_status", '=', 1)
//            ->where("work.hospital_id", '=', $hospital_id)
//            ->where("order.order_status", '<=', 1)
//            ->get();

//        Tool::ends();
        foreach ($res as $v) {
            if ($v->age < 18) {
                $age_value[0] += 1;
            } elseif ($v->age > 18 && $v->age < 30) {
                $age_value[1] += 1;
            } elseif ($v->age >= 30 && $v->age < 40) {
                $age_value[2] += 1;
            } elseif ($v->age >= 40 && $v->age <= 60) {
                $age_value[3] += 1;
            } elseif ($v->age > 60 && $v->age <= 80) {
                $age_value[4] += 1;
            } elseif ($v->age > 80) {
                $age_value[5] += 1;
            }
        }
        $list['age_name'] = $age_name;
        $list['age_value'] = $age_value;
        return $list;
    }


    /***
     * @param $w
     * 工作室参与的咨询数
     */
    public function getWorkConsultNumber($w)
    {
//        Tool::start();
        $res = (new Order())->whereIn("work_id", $w)->whereIn("order_type", [3, 4])->where("order_status", '<', 2)->where("pay_status", '=', 1)->groupBy("work_id")->get()->count();//->count("work.id");
//        $res = (new DoctorWorks())
//            ->from("c_doctor_works as work")
//            ->rightJoin("c_orders as order", 'order.work_id', '=', 'work.id')
//            ->distinct("order.work_id")
//            ->whereIn("work.id", $w)->whereIn("order.order_type", [3, 4])->where("order.pay_status", '=', 1)->get();//->count("work.id");
//        Tool::ends();
        return $res;
//        return Order::whereIn("work_id",$w)->whereIn("order_type", [3, 4])->where("pay_status",'=',1)->groupBy("work_id")->count("work_id");
    }
    /***
     * @param $work_ids
     * 获取病种统计图
     */
    public function getDiseaseTypesList($w_ids)
    {
        if (empty($w_ids)) {
            return [];
        }
        $list = DB::table('c_address_book_labels as c')
            ->select('c.label_name', "c.lab_type")
            ->where("c.lab_type", '=', 1)
            ->whereIn("c.work_id", $w_ids)
            ->groupBy('c.label_name')
            ->get();
        $lit = [];
        foreach ($list as $k=>$v) {
            $vall = DB::table('c_address_book_relate_labels as m')
                ->leftJoin('c_address_books as o', 'm.address_book_id', '=', 'o.id')
                ->leftJoin('c_address_book_labels as c', 'm.address_book_label_id', '=', 'c.id')
                ->where("c.lab_type", '=', 1)
                ->where('label_name', '=', $v->label_name)
                ->groupBy('o.user_id')
                ->whereIn("m.work_id", $w_ids)
                ->get()
                ->count();
            if($vall ==0){
                continue;
            }
            $lit[$k]['name'] = $v->label_name;
            $lit[$k]['value'] = $vall;
        }
        $name = [];
        $value = [];
        if(!empty($lit)){
            $order_count = array_column($lit, 'value');
            array_multisort($order_count, SORT_DESC, $lit);
            $lit =  array_slice($lit,0,6);
            foreach ($lit as $vv){
                $name[] = $vv['name'];
                $value[] = $vv['value'];
            }
        }
        $val['name'] = $name;
        $val['value'] = $value;
        $result['list'] = $lit;
        $result['val'] = $val;
        return $result;
//        $list = DB::table('c_address_book_relate_labels as m')
//            ->select('c.label_name','m.address_book_id',"c.lab_type","o.user_id",DB::raw('count(c.label_name) as order_count'))
//            ->leftJoin('c_address_books as o', 'm.address_book_id', '=', 'o.id')
//            ->leftJoin('c_address_book_labels as c', 'm.address_book_label_id', '=', 'c.id')
//            ->where("c.lab_type", '=',1)
//            ->groupBy('c.label_name')
//            ->whereIn("m.work_id", $w_ids)
//            ->orderBy('order_count', 'desc')
//            ->limit(6)->get();
//        dd($list);die();
    }


    /**
     * @param $w_ids
     * @return array
     * 工作室创作排名
     */
    public function getWorkCreateNumber($w_ids)
    {
        if (empty($w_ids)) {
            return [];
        }
        $works = DB::table('c_doctor_works as m')
            ->select('m.work_name', 'm.id', 'm.clinic_id', 'c.classify_name')
            ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')
            ->whereIn("m.id", $w_ids)
            ->get()->toArray();
//        $works = DoctorWorks:: ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')whereIn("id", $w_ids)->select("work_name", "id")->get()->toArray();
        foreach ($works as &$v) {
            $art_count = Article::where("work_id", '=', $v->id)->count();
            $course_count = Course::where("work_id", '=', $v->id)->where("audit_status",'=',2)->count();
            $v->order_count = $art_count + $course_count;
        }
        $order_count = array_column($works, 'order_count');
        array_multisort($order_count, SORT_DESC, $works);
        return array_slice($works,0,3);
    }





    /**
     * @param $w_ids
     * @return array|\Illuminate\Support\Collection
     * 工作室咨询订单排名
     */
    public function getConsultRankList($w_ids)
    {
        if (empty($w_ids)) {
            return [];
        }
//        $list = DB::table('c_doctor_works as m')
//            ->select('m.work_name', 'm.id', 'm.clinic_id', 'c.classify_name', DB::raw('count(o.id) as order_count'))
//            ->leftJoin('c_orders as o', 'm.id', '=', 'o.work_id')
//            ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')
//            ->whereIn("order_type", [3, 4])
//            ->whereIn("m.id", $w_ids)
//            ->groupBy('m.id')
//            ->where("o.pay_status",'=',1)
//            ->where("o.order_status",'<',2)
//            ->orderBy('order_count', 'desc')
//            ->limit(3)
//            ->get();
        $list = (new DoctorWorks())->withCount('order')
//                ->select('c_doctor_works.work_name', 'c_doctor_works.id', 'c_doctor_works.clinic_id','d.real_name', 'c.classify_name')
//                ->join("c_orders as order",'order.id','=','order_goods.order_id')
            ->addSelect('d.real_name','c.classify_name')
            ->leftJoin('c_clinic_categories as c', 'c_doctor_works.clinic_id', '=', 'c.id')
            ->leftJoin('c_doctors as d', 'c_doctor_works.id', '=', 'd.work_id')
            ->whereIn("c_doctor_works.id", $w_ids)
            ->where("d.is_admin",'=',1)
            ->groupBy('c_doctor_works.id')
            ->orderBy('order_count', 'desc')
            ->limit(3)
            ->get();
//        $str = '('.implode(',',$w_ids).')';
//        $list =  DB::select("select c_doctor_works.*,(SELECT count(c_orders.id)as count FROM c_orders where c_orders.work_id =c_doctor_works.id) as count  FROM c_doctor_works where c_doctor_works.id in $str   ORDER BY count desc limit 3");
        return $list;
    }

    /**
     * @param $w_ids
     * @return array|\Illuminate\Support\Collection
     * 工作室患者排名
     */
    public function getPatientNumList($w_ids)
    {
        if (empty($w_ids)) {
            return [];
        }
        $list = DB::table('c_doctor_works as m')
            ->select('m.work_name', 'm.id', 'm.clinic_id', 'c.classify_name', DB::raw('count(o.id) as order_count'))
            ->leftJoin('c_address_books as o', 'm.id', '=', 'o.work_id')
            ->leftJoin('c_clinic_categories as c', 'm.clinic_id', '=', 'c.id')
            ->whereIn("m.id", $w_ids)
            ->groupBy('m.id')
            ->orderBy('order_count', 'desc')
            ->limit(3)
            ->get();
        return $list;
    }

//    日期递减
    public function getDayBeforeDays($n) {
        return \Carbon\Carbon::now()->subDays($n)->toDateString();
    }


}
